package be.kuleuven.thesis.pages;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import be.kuleuven.thesis.R;
import be.kuleuven.thesis.databases.AristoMusicManager;
import be.kuleuven.thesis.framework.Song;
import be.kuleuven.thesis.log.Logger;
import be.kuleuven.thesis.widget.SearchSongAdapter;

public class Search extends Activity{
	private EditText searchField;
	private LinearLayout searchTextLayout;
	private ArrayAdapter<Song> songAdapter;
	private List<Song> songs = new ArrayList<Song>();
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        
        defineUI();
        
        ListView resultList = (ListView)findViewById(R.id.resultList);
        songAdapter = new SearchSongAdapter(this, songs);
        resultList.setAdapter(songAdapter); 
	}
	
	@Override
	public void onResume() {
		super.onResume();
		GenerecsTabActivity parentActivity;
        parentActivity = (GenerecsTabActivity) this.getParent();
        parentActivity.setOnTabChangedListener(new OnTabChangeListener() {		
			@Override
			public void onTabChanged(String tabId) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(searchField.getWindowToken(), 0);
			}
		});
	}
	
	private void defineUI() {
		Button clearButton = (Button)findViewById(R.id.clear_button);
		clearButton.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View view) {
				searchField.setText("");
				Logger.getInstance().log("Search","User pressed clear", null);
			}
		});
		
		Button searchButton = (Button)findViewById(R.id.search_button);
		searchButton.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View view) {
				search(searchField.getText().toString());
				Logger.getInstance().log("Search","User searched for: "+searchField.getText().toString(), null);
			}
		});
		
		searchField = ((EditText)findViewById(R.id.search_field));
		searchField.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
						(keyCode == KeyEvent.KEYCODE_ENTER)) {
					search(searchField.getText().toString());
					return true;
				}
				return false;
			}
		});
		searchField.setOnEditorActionListener(new EditText.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					search(searchField.getText().toString());
					return true;
				}
				return false;
			}
		});
		searchTextLayout = (LinearLayout) findViewById(R.id.search_text_layout);
		searchTextLayout.setVisibility(LinearLayout.GONE);
	}
	
	private void search(String query) {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(searchField.getWindowToken(), 0);
		TextView searchText = (TextView) findViewById(R.id.search_text);
		ProgressBar searchProgress = (ProgressBar) findViewById(R.id.search_progress);
		
		songs.clear();
		songAdapter.notifyDataSetChanged();
		searchText.setText("Searching...");
		searchTextLayout.setVisibility(View.VISIBLE);
		searchProgress.setVisibility(ProgressBar.VISIBLE);
		new SearchSongsTask().execute(query);		
	}
	
	private class SearchSongsTask extends AsyncTask<String, Song, Void> {
		List<Song> resultList;
		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(String ...query) {
			resultList = AristoMusicManager.getInstance().search(query[0]);
			return null;
		}

		// can use UI thread here
		@Override
		protected void onPostExecute(final Void unused) {
			if(resultList == null) {
				Toast.makeText(getApplicationContext(), "Cream cannot connect with the AristoMusic database, please check your internet connection.", Toast.LENGTH_LONG).show();
			}
			TextView searchText = (TextView) findViewById(R.id.search_text);
			if(resultList == null || resultList.isEmpty()) {
				searchText.setText(R.string.no_results);
				ProgressBar searchProgress = (ProgressBar) findViewById(R.id.search_progress);
				searchProgress.setVisibility(View.GONE);
			}
			else {
				searchTextLayout.setVisibility(LinearLayout.GONE);
				songs.addAll(resultList);
			}
				
			songAdapter.notifyDataSetChanged();
		}
	}
	
	public void switchTab(int indexTabToSwitchTo){
        GenerecsTabActivity parentActivity;
        parentActivity = (GenerecsTabActivity) this.getParent();
        parentActivity.switchTab(indexTabToSwitchTo);
	}
	
	@Override
	public void onBackPressed() {
		GenerecsTabActivity.tabActivity.back();
		return;
	}
}
